package com.tech.view.panel;

import com.tech.repository.dto.GoodsInfo;
import com.tech.repository.entity.Goods;
import com.tech.repository.entity.GoodsImage;
import com.tech.repository.entity.User;
import com.tech.repository.session.UserSession;
import com.tech.service.GoodsImageService;
import com.tech.service.GoodsService;
import com.tech.service.impl.ServiceImplFactory;
import com.tech.util.LogProcessUtil;
import com.tech.view.common.ButtonFactory;
import com.tech.view.common.ColorUtil;
import com.tech.view.common.ImageSizeAdjuster;
import com.tech.view.common.ResourcesUtil;
import com.tech.view.component.button.ImageUploadButton;
import com.tech.view.component.button.SimpleIconButton;
import com.tech.view.component.input.LabelComboBox;
import com.tech.view.component.input.LabelInputTextField;
import com.tech.view.component.input.LabelIntegerInputField;
import com.tech.view.frame.MainFrame;
import org.jdesktop.swingx.JXTextArea;
import org.jdesktop.swingx.JXTextField;
import org.jdesktop.swingx.VerticalLayout;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

/**
 * 商品发布面板
 */
public class GoodsSendPanel extends JPanel implements PanelLifeCycle {
	private final static Logger LOG = LogProcessUtil.getLogger(GoodsSendPanel.class.getName());
	private GoodsService goodsService = ServiceImplFactory.getGoodsService();
	private GoodsImageService goodsImageService = ServiceImplFactory.getGoodsImageService();
	private MainFrame frame;
	/**
	 * 编辑时传入的商品信息
	 */
	private GoodsInfo goodsInfo;
	private JPanel topPanel;
	private JPanel contentPanel;
	private JPanel contentBottomPanel;
	private JPanel leftPanel;
	private SimpleIconButton cancelButton;
	private JButton saveDraftButton;
	private JButton sendButton;
	private JXTextField goodsNameField;
	private JXTextArea goodsIntroduceArea;
	// 图片上传
	private ImageUploadButton[] uploadImageButtons;
	private int currentCount; //当前显示的图片上传按钮数量

	private LabelInputTextField priceField;
	private LabelInputTextField secondPriceField;
	private LabelIntegerInputField countField;
	private LabelComboBox<Goods.Condition> goodsCondition;
	private LabelComboBox<Goods.SendMode> goodsSendMode;

	public GoodsSendPanel(MainFrame frame) {
		this(frame, null);
	}

	public GoodsSendPanel(MainFrame frame, GoodsInfo goodsInfo) {
		this.frame = frame;
		this.goodsInfo = goodsInfo;
	}

	private void initService() {

	}

	private void initComponents() {


		cancelButton = new SimpleIconButton(new ImageIcon(ResourcesUtil.getImage(ResourcesUtil.Image.CANCEL)));
		cancelButton.setBackground(ColorUtil.BACKGROUND_COLOR);
		saveDraftButton = ButtonFactory.createPlainButton("存草稿", ColorUtil.LIGHT_BLUE_COLOR, 90, 32);

		sendButton = ButtonFactory.createDefaultButton("发布", ColorUtil.LIGHT_BLUE_COLOR, 90, 32);

		goodsNameField = new JXTextField("填入商品名");
		goodsIntroduceArea = new JXTextArea("买家都关心书的入手渠道、新旧程度、转手原因...");
		goodsIntroduceArea.setLineWrap(true);
		goodsIntroduceArea.setWrapStyleWord(true);

		uploadImageButtons = new ImageUploadButton[3];
		for (int i = 0; i < 3; i++)
			uploadImageButtons[i] = new ImageUploadButton();

		priceField = new LabelInputTextField("商品原价");
		secondPriceField = new LabelInputTextField("商品二手价");
		countField = new LabelIntegerInputField("数量");
		goodsCondition = new LabelComboBox<>("使用状况", Goods.Condition.toArray());
		goodsSendMode = new LabelComboBox<>("配送方式", Goods.SendMode.toArray());

		// 如果是编辑页面
		if (goodsInfo != null) {
			sendButton.setText("保存");

			Goods goods = goodsInfo.getGoods();
			List<GoodsImage> images = goodsImageService.getGoodsImageListById(goods.getGid());
			goodsInfo.setImages(images); // 修改需要指定imid

			goodsNameField.setText(goods.getGname());
			goodsIntroduceArea.setText(goods.getGintroduce());
			// 存在图片按钮就设置为按钮背景
			if (images != null && images.size() != 0) {
				int len = Math.min(images.size(), uploadImageButtons.length);
				for (int i = 0; i < len; i++)
					uploadImageButtons[i].setImage(images.get(i).getImage());
			}
			priceField.setText(String.format("%.2f", goods.getGprice()));
			secondPriceField.setText(String.format("%.2f", goods.getGsecprice()));
			countField.setNum(goods.getGcount());
		}
	}

	private void initView() {
		setLayout(new BorderLayout());
		setPreferredSize(new Dimension(860, 600));
		VerticalLayout verticalLayout = new VerticalLayout(10);

		topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
		topPanel.add(cancelButton);
		topPanel.add(Box.createHorizontalStrut(500));
		topPanel.add(saveDraftButton);
		topPanel.add(sendButton);


		leftPanel = new JPanel();
		// 一开始只显示一个按钮
		leftPanel.add(uploadImageButtons[0]);
		if (goodsInfo != null) {//编辑页面就把其他图片显示出来
			int maxIndex = 1;
			for (int i = 1; i < uploadImageButtons.length; i++)
				if (uploadImageButtons[i].getImage() != null) {
					leftPanel.add(uploadImageButtons[i]);
					maxIndex = i;
				}
			currentCount = maxIndex + 1;
		}

		currentCount++; //一个按钮
		JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 0));
		JPanel panel1 = new JPanel(verticalLayout);
		JPanel panel2 = new JPanel(verticalLayout);
		// 为了让左边3个输入框和右边2两输入框顶部对齐，需要设置统一大小
		panel1.setPreferredSize(new Dimension(150, 100));
		panel2.setPreferredSize(new Dimension(150, 100));
		panel1.add(priceField);
		panel1.add(secondPriceField);
		panel1.add(countField);
		panel2.add(goodsCondition);
		panel2.add(goodsSendMode);
		rightPanel.add(panel1);
		rightPanel.add(panel2);
		contentBottomPanel = new JPanel(new BorderLayout());
		contentBottomPanel.add(leftPanel, BorderLayout.WEST);
		contentBottomPanel.add(rightPanel, BorderLayout.EAST);


		contentPanel = new JPanel(verticalLayout);
		contentPanel.add(goodsNameField);
		JScrollPane scrollPane = new JScrollPane(goodsIntroduceArea);
		scrollPane.setPreferredSize(new Dimension(860, 350));
		contentPanel.add(scrollPane);
		contentPanel.add(contentBottomPanel);

		add(topPanel, BorderLayout.NORTH);
		add(contentPanel);
	}

	private void setListeners() {
		cancelButton.addActionListener(e -> frame.switchContentPanel(new IndexPanel(frame)));
		sendButton.addActionListener(e -> {
			String name = goodsNameField.getText();
			String introduce = goodsIntroduceArea.getText();
			double price = Double.parseDouble(priceField.getText());
			double secondPrice = Double.parseDouble(secondPriceField.getText());
			int count = Integer.parseInt(countField.getText());
			Goods.Condition condition = goodsCondition.getSelected();
			Goods.SendMode sendMode = goodsSendMode.getSelected();
			User user = UserSession.user;

			Goods goods = new Goods(null, name, 0, introduce, price,
					secondPrice, user.getUid(), condition, sendMode, user.getUname(), count, new Date());
			// TODO 数据未曾检查
			if (goodsInfo == null) { //添加
				// 添加商品
				if (goodsService.addGoods(goods) != 1) {
					JOptionPane.showConfirmDialog(frame, "商品添加失败", "失败", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE);
					LOG.warning("商品添加失败\n" + goods);
					return;
				}
				// 添加商品图片
				if (uploadImageButtons[0].getImage() != null){
					long createTime = System.currentTimeMillis();
					for (ImageUploadButton b : uploadImageButtons) {
						if (b.getSelectCount() != 0) {
							BufferedImage image = b.getImage();
							// 存储前先将图片缩放到合适大小，这里只限制宽度
							image = ImageSizeAdjuster.adjust(image);
							GoodsImage goodsImage = new GoodsImage(null, goods.getGid(), image, b.getSuffix(),createTime);
							goodsImageService.addGoodsImage(goodsImage);
						}
					}
				}

				JOptionPane.showConfirmDialog(frame, "商品添加成功", "成功", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);
			} else { // 修改
				goods.setGid(goodsInfo.getGoods().getGid());
				if (goodsService.updateGoods(goods)) {
					long updateTime = System.currentTimeMillis();
					List<GoodsImage> images = goodsInfo.getImages();
					for (int i = 0; i < uploadImageButtons.length; i++) {
						if (uploadImageButtons[i].getSelectCount() != 0) goodsImageService.
								updateGoodsImage(new GoodsImage(images.get(i).getImid(), goods.getGid(), uploadImageButtons[i].getImage(), uploadImageButtons[i].getSuffix(),updateTime));
					}

					JOptionPane.showConfirmDialog(frame, "商品编辑成功", "成功", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);
				} else {
					LOG.warning(goodsInfo.getGoods().getGid() + " 号商品数据修改失败，修改失败的数据：\n" + goods);
				}
			}
			frame.switchContentPanel(new IndexPanel(frame));
		});

		// 选择一个图片后出现新的按钮
		for (ImageUploadButton b : uploadImageButtons) {
			b.setTask(() -> {
				if (currentCount < uploadImageButtons.length) {
					leftPanel.add(uploadImageButtons[currentCount]);
					currentCount++;
					leftPanel.revalidate();
				} else {
					// 删掉这个没用的任务
					for (ImageUploadButton b2 : uploadImageButtons)
						b2.setTask(null);
				}
			});
		}
	}

	@Override
	public void start() {
		initService();
		initComponents();
		setListeners();
		initView();
	}

	@Override
	public boolean end() {
		// TODO 离开发旧书页面之前，应该提示是否保存草稿

		return false;
	}
}
